package ystp.controller;


import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ystp.model.Chuangxinchanpin;
import ystp.model.Chuangxinchanpinjieguo;
import ystp.model.Ysrenyuanfenpei;
import ystp.model.Ysxiangmu;
import ystp.service.*;
import ystp.support.JsonResult;
import ystp.support.StringHandle;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("chuangxinchanpinjieguo")
public class ChuangxinchanpinjieguoController {

    @Resource
    ChuangxinchanpinjieguoService ddService;

    @Resource
    ChuangxinchanpinService ddChuangxinchanpinService;

    @Resource
    YsuserService ddYsuserService;

    @Resource
    YsrenyuanfenpeiService ddYsrenyuanfenpeiService;

    @Resource
    YsxiangmuService ddYsxiangmuService;

    public Logger log = LoggerFactory.getLogger(ChuangxinchanpinjieguoController.class);


    @RequestMapping("getChuangxinchanpinResultCount")
    public JsonResult<?> getChuangxinchanpinResultCount(@RequestParam("xiangmuid") String ppxiangmuId,
                                             @RequestParam("userid") String ppuserId){
        try {
            Integer mmTongyishu=ddService.getChuangxinchanpinResultCount(ppxiangmuId,ppuserId,"1");
            Integer mmButongyishu=ddService.getChuangxinchanpinResultCount(ppxiangmuId,ppuserId,"0");
            Integer mmTotal=ddChuangxinchanpinService.getChuangxinCount(ppxiangmuId);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("tongyiShu", mmTongyishu);
            mmMap.put("butongyiShu", mmButongyishu);
            mmMap.put("total", mmTotal);
            return JsonResult.getSuccessResult(mmMap);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("chuangxinchanpinjieguo/getChuangxinchanpinResultCount:error",e);
            return JsonResult.getErrorResult("chuangxinchanpinjieguo/getChuangxinchanpinResultCount:error " + e.getMessage());
        }
    }

    @RequestMapping("toupiao")
    public JsonResult<?> toupiao(@RequestParam("id") String ppdetailId,
                                 @RequestParam("userid") String ppuserId,
                                 @RequestParam("result") String ppresult){
        try {
            Chuangxinchanpinjieguo mmChuangxinchanpinjieguo = new Chuangxinchanpinjieguo();
            Chuangxinchanpin mmChuangxinchanpin = ddChuangxinchanpinService.findOne(ppdetailId);

            Ysxiangmu mmYsxiangmu=ddYsxiangmuService.findOne(mmChuangxinchanpin.getXiangmuid());
            if(mmYsxiangmu.getIsactived()!=1){
                return JsonResult.getErrorResult("表决失败，投票尚未启动");
            }

            if (ddService.checkExistByUserId(ppdetailId,ppuserId)!=null){
                String mmId = ddService.checkExistByUserId(ppdetailId,ppuserId).getId();
                mmChuangxinchanpinjieguo = ddService.findOne(mmId);
                mmChuangxinchanpinjieguo.setUserid(ppuserId);
                mmChuangxinchanpinjieguo.setResult(ppresult);
                return ddService.modify(mmChuangxinchanpinjieguo) == true ? JsonResult.getSuccessResult("表决成功")
                        : JsonResult.getErrorResult("表决失败");
            }else{
                mmChuangxinchanpinjieguo.setId(UUID.randomUUID().toString());
                mmChuangxinchanpinjieguo.setDetailid(ppdetailId);
                mmChuangxinchanpinjieguo.setCreatetime(new Date());
                mmChuangxinchanpinjieguo.setUserid(ppuserId);
                mmChuangxinchanpinjieguo.setResult(ppresult);
                return ddService.add(mmChuangxinchanpinjieguo) == true ? JsonResult.getSuccessResult("表决成功")
                        : JsonResult.getErrorResult("表决失败");
            }

        }catch (Exception e) {
            e.printStackTrace();
            log.error("Chuangxinchanpinjieguo/toupiao:error",e);
            return JsonResult.getErrorResult("Chuangxinchanpinjieguo/toupiao:error " + e.getMessage());
        }
    }

    @RequestMapping("submit")
    public JsonResult<?> submit(
            @RequestParam("xiangmuid") String ppxiangmuId,
            @RequestParam("userid") String ppuserId,
            HttpServletRequest request){
        try{
            List<Ysrenyuanfenpei> list=ddYsrenyuanfenpeiService.findbyUserIDandXiangmuId(ppuserId,ppxiangmuId);
            if(list.size()<1){
                return JsonResult.getErrorResult("提交失败，人员-项目分配信息不存在");
            }

            Integer mmTotal=ddChuangxinchanpinService.getChuangxinCount(ppxiangmuId);
            Integer mmTongyishu=ddService.getChuangxinchanpinResultCount(ppxiangmuId,ppuserId,"1");
            if (mmTongyishu<mmTotal){
                return JsonResult.getErrorResult("提交失败，请全部选择通过。");
            }

            Ysrenyuanfenpei mmRenyuanfenpei=ddYsrenyuanfenpeiService.findOne(list.get(0).getId());
            mmRenyuanfenpei.setIssubmit(1);
            mmRenyuanfenpei.setUpdatetime(new Date());
            HttpSession session = request.getSession();
            mmRenyuanfenpei.setUpdateby(session.getAttribute("Id").toString());
            return ddYsrenyuanfenpeiService.update(mmRenyuanfenpei)==true? JsonResult.getSuccessResult("提交成功")
                    : JsonResult.getErrorResult("提交失败");
        }catch (Exception e) {
            e.printStackTrace();
            log.error("chuangxinchanpinjieguo/submit:error",e);
            return JsonResult.getErrorResult("chuangxinchanpinjieguo/submit:error " + e.getMessage());
        }
    }

    // 导出某个委员的签字表
    @RequestMapping("qianzibiao")
    public void qianzibiao(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam("xiangmuid") String ppxiangmuid,
                           @RequestParam("xiangmuleixing") String ppxiangmuleixing,
                           @RequestParam("userid") String ppuserid) {
        try {
            ddService.daochuqianzibiao(ppxiangmuid, ppuserid, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("findHuizongbiaolist")
    public JsonResult<?> findHuizongbiaolist(@RequestParam("xiangmuid") String ppxiangmuid){
        try {
            List<Ysrenyuanfenpei> mmUserList=ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
            Double mm=((double)1/(double)2)*mmUserList.size();
            int mmTongguopiaoshu=(int)Math.ceil(mm);
            List<Map<String,Object>> mmList=ddService.getHuizongbiao(ppxiangmuid);

            for (int i=0; i<mmList.size();i++) {
                String mmDetailId = mmList.get(i).get("id").toString();
                String mmPiaoshu = mmList.get(i).get("piaoshu")==null?"0":mmList.get(i).get("piaoshu").toString();
                String mmPiaoshuText = mmPiaoshu + "/" + String.valueOf(mmUserList.size());
                String mmJieguotext="不通过";
                if(Integer.valueOf(mmPiaoshu)>=mmTongguopiaoshu){
                    mmJieguotext="通过";
                }
                mmList.get(i).put("paiming",i+1);
                mmList.get(i).put("piaoshu",mmPiaoshuText);
                mmList.get(i).put("jieguo",mmJieguotext);
            }

            return JsonResult.getSuccessResult(mmList);

        }catch (Exception e) {
            e.printStackTrace();
            log.error("chuangxinchanpinjieguo/findHuizongbiaolist:error",e);
            return JsonResult.getErrorResult("chuangxinchanpinjieguo/findHuizongbiaolist:error " + e.getMessage());
        }
    }

    @RequestMapping("huizongbiao")
    public void huizongbiao(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam("xiangmuid") String ppxiangmuid,
                            @RequestParam("xiangmuleixing") String ppxiangmuleixing){
        response.reset();
        response.setContentType("application/x-download;charset=utf-8");
        OutputStream os=null;
        WritableWorkbook wbook=null;

        List<Ysrenyuanfenpei> mmUserList=ddYsrenyuanfenpeiService.findUserByXiangmuId(ppxiangmuid);
        Double mm=((double)1/(double)2)*mmUserList.size();
        int mmTongguopiaoshu=(int)Math.ceil(mm);
        List<Map<String,Object>> mmList=ddService.getHuizongbiao(ppxiangmuid);

        for (int i=0; i<mmList.size();i++) {
            String mmDetailId = mmList.get(i).get("id").toString();
            String mmPiaoshu = mmList.get(i).get("piaoshu")==null?"0":mmList.get(i).get("piaoshu").toString();
            String mmPiaoshuText = mmPiaoshu + "/" + String.valueOf(mmUserList.size());
            String mmJieguotext="不通过";
            if(Integer.valueOf(mmPiaoshu)>=mmTongguopiaoshu){
                mmJieguotext="通过";
            }
            mmList.get(i).put("paiming",i+1);
            mmList.get(i).put("piaoshu",mmPiaoshuText);
            mmList.get(i).put("jieguo",mmJieguotext);
        }

        try
        {
            os = new BufferedOutputStream(response.getOutputStream());//得到输出流的语句
            //response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            SimpleDateFormat mmDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String wenjiantitle = "东部战区总医院南京市生物医药创新产品目录汇总表"+ StringHandle.tiemString(); //文件名
            String tmptitle = "东部战区总医院南京市生物医药创新产品目录投票表"; // 标题
            response.setHeader("Content-disposition", "attachment; filename="+new String(wenjiantitle.getBytes(),"iso8859-1")+".xls");// 设定输出文件头
            response.setContentType("application/vnd.ms-excel");// 定义输出类型
            wbook = Workbook.createWorkbook(os); // 建立excel文件
            WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
            // 设置excel标题
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 20,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //设置表格样式

            WritableCellFormat wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN); // 添加边框
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);

            WritableCellFormat wcfFC3 = new WritableCellFormat(wfont);
            wcfFC3.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC3.setAlignment(Alignment.CENTRE);
            //wcfFC.setBackground(Colour.AQUA);
            Label label=new Label(0, 0, tmptitle, wcfFC3);

            WritableCellFormat cellFormat=new WritableCellFormat();
            cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
            cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            cellFormat.setWrap(true);
            cellFormat.setFont(wfont);
            label.setCellFormat(cellFormat);
            wsheet.addCell(label);
            wsheet.addCell(new Label(0, 0, tmptitle, wcfFC3));
            wsheet.setRowView(0,800); //第一行高度
            wsheet.setColumnView(0,20); //宽度
            wsheet.mergeCells(0, 0, 11, 0);  //合并单元格(第一列的第一行和第十三列的第一行合并)
            wsheet.setColumnView(1,20); //宽度
            wsheet.setColumnView(2,20); //宽度
            wsheet.setColumnView(3,20); //宽度
            wsheet.setColumnView(4,20); //宽度
            wsheet.setColumnView(5,20); //宽度
            wsheet.setColumnView(6,20); //宽度
            wsheet.setColumnView(7,20); //宽度
            wsheet.setColumnView(8,20); //宽度
            wsheet.setColumnView(9,20); //宽度
            wsheet.setColumnView(10,20); //宽度
            wsheet.setColumnView(11,20); //宽度

            // 开始生成主体内容
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 12,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);
            // 不需要边框和居中的样式
            WritableCellFormat wcfFC2 = new WritableCellFormat(wfont);
            wcfFC2 = new WritableCellFormat(wfont);
            wcfFC2.setWrap(true);

            wsheet.addCell(new Label(0, 1, "排名",wcfFC));
            wsheet.mergeCells(0, 1, 0, 2);

            wsheet.addCell(new Label(1, 1, "序号",wcfFC));
            wsheet.mergeCells(1, 1, 1, 2);

            wsheet.addCell(new Label(2, 1, "药品名称",wcfFC));
            wsheet.mergeCells(2, 1, 2, 2);

            wsheet.addCell(new Label(3, 1, "规格",wcfFC));
            wsheet.mergeCells(3, 1, 3, 2);

            wsheet.addCell(new Label(4, 1, "单位",wcfFC));
            wsheet.mergeCells(4, 1, 4, 2);

            wsheet.addCell(new Label(5, 1, "价格（元）",wcfFC));
            wsheet.mergeCells(5, 1, 5, 2);

            wsheet.addCell(new Label(6, 1, "生产厂家",wcfFC));
            wsheet.mergeCells(6, 1, 6, 2);

            wsheet.addCell(new Label(7, 1, "执行时间",wcfFC));
            wsheet.mergeCells(7, 1, 7, 2);

            wsheet.addCell(new Label(8, 1, "完成金额",wcfFC));
            wsheet.mergeCells(8, 1, 9, 1);

            wsheet.addCell(new Label(8, 2, "院本部",wcfFC));

            wsheet.addCell(new Label(9, 2, "秦淮",wcfFC));

            wsheet.addCell(new Label(10, 1, "委员表决票数(同意数/总票数)",wcfFC));
            wsheet.mergeCells(10, 1, 10, 2);

            wsheet.addCell(new Label(11, 1, "表决结果",wcfFC));
            wsheet.mergeCells(11, 1, 11, 2);

            // 表头结束

            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 12,WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
            wcfFC = new WritableCellFormat(wfont);
            wcfFC.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
            wcfFC.setAlignment(Alignment.CENTRE);
            wcfFC.setWrap(true);

            int count=mmList.size();
            int mmKaishihang=3;

            for (int i = 0; i < mmList.size(); i++) {
                Map<String,Object> mmMap = mmList.get(i);
                if (mmMap!=null){
                    String mmPaiming = mmMap.get("paiming")==null ? "" :mmMap.get("paiming").toString();
                    String mmXuhao = mmMap.get("ordernumber")==null ? "" :mmMap.get("ordernumber").toString();
                    String mmyaopinmingcheng=mmMap.get("yaopinmingcheng")==null ? "" :mmMap.get("yaopinmingcheng").toString();
                    String mmGuige=mmMap.get("guige")==null ? "" :mmMap.get("guige").toString();
                    String mmDanwei=mmMap.get("danwei")==null ? "" :mmMap.get("danwei").toString();
                    String mmJiage=mmMap.get("jiage")==null ? "" :mmMap.get("jiage").toString();
                    String mmShengchanchangjia=mmMap.get("shengchanchangjia")==null ? "" :mmMap.get("shengchanchangjia").toString();
                    String mmZhixingshijian=mmMap.get("zhixingshijian")==null ? "" :mmMap.get("zhixingshijian").toString();
                    String mmYuanbenbu=mmMap.get("yuanbenbu")==null ? "" :mmMap.get("yuanbenbu").toString();
                    String mmQinhuai=mmMap.get("qinhuai")==null ? "" :mmMap.get("qinhuai").toString();
                    String mmresult=mmMap.get("result")==null ? "" :mmMap.get("result").toString();
                    String mmbiaojueren=mmMap.get("username")==null ? "" :mmMap.get("username").toString();
                    String mmpiaoshu=mmMap.get("piaoshu")==null ? "" :mmMap.get("piaoshu").toString();
                    String mmjieguo=mmMap.get("jieguo")==null ? "" :mmMap.get("jieguo").toString();

                    wsheet.addCell(new Label(0, mmKaishihang,mmPaiming,wcfFC));
                    wsheet.addCell(new Label(1, mmKaishihang,mmXuhao,wcfFC));
                    wsheet.addCell(new Label(2, mmKaishihang,mmyaopinmingcheng,wcfFC));
                    wsheet.addCell(new Label(3, mmKaishihang,mmGuige,wcfFC));
                    wsheet.addCell(new Label(4, mmKaishihang,mmDanwei,wcfFC));
                    wsheet.addCell(new Label(5, mmKaishihang,mmJiage,wcfFC));
                    wsheet.addCell(new Label(6, mmKaishihang,mmShengchanchangjia,wcfFC));
                    wsheet.addCell(new Label(7, mmKaishihang,mmZhixingshijian,wcfFC));
                    wsheet.addCell(new Label(8, mmKaishihang,mmYuanbenbu,wcfFC));
                    wsheet.addCell(new Label(9, mmKaishihang,mmQinhuai,wcfFC));
                    wsheet.addCell(new Label(10, mmKaishihang,mmpiaoshu,wcfFC));
                    if("通过".equals(mmjieguo)){
                        wsheet.addCell(new Label(11, mmKaishihang,mmjieguo,wcfFC));
                    }else {

                        WritableFont wfont1 = new jxl.write.WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
                        WritableCellFormat wcfFC1 = new WritableCellFormat(wfont1);
                        wcfFC1.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
                        wcfFC1.setVerticalAlignment(VerticalAlignment.CENTRE);   //设置居中对齐
                        wcfFC1.setAlignment(Alignment.CENTRE);
                        wcfFC1.setWrap(true);

                        wsheet.addCell(new Label(11, mmKaishihang,mmjieguo,wcfFC1));
                    }
                    mmKaishihang = mmKaishihang+1;
                }
            }
            wbook.write(); // 写入文件
            wbook.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }finally{
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
